package cn.hanna.springcloud.mybl.impl;



import cn.hanna.springcloud.mybl.LoadBalance;
import com.sun.org.apache.xpath.internal.WhitespaceStrippingElementMatcher;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;


import java.lang.annotation.Annotation;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author smileha
 * @create 2021-10-17 15:29
 * @description  自定义轮询算法
 */
@Component
public class MyRoundLoadBalance implements LoadBalance {

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    // 获取应该请求的服务的索引
    private final int getInstanceIndex(int modulo){
        int current;
        int next;
        do {
            current = atomicInteger.get();
//            next = (current + 1) % modulo; 方式一：
            next = current >= 2147483647 ? 0 : current + 1;
        } while (!this.atomicInteger.compareAndSet(current,next));
        System.out.println("*************这是第"+next+"次访问**********");
        return next;
    }

    @Override
    public ServiceInstance getServiceInstance(List<ServiceInstance> instances) {
        int size = instances.size();
//        int index = getInstanceIndex(size); 方式一：
        int index = getInstanceIndex(size) % size;
        ServiceInstance instance = instances.get(index);
        return instance;
    }
}
